﻿#include "json_handle.h"
#include <QTextCodec>
#include <QDebug>

Json_handle::Json_handle(QObject *parent) :
    QObject(parent)
{
    //jsontest();
//    QString login = order_login("admin", "0000", "94");
//    int crcnum = order_crcexplain(login);
//    QString sent = order_makeup(crcnum, 254, login);
//    QStringList keylist = getJsonObjectNameString(sent);
//    qDebug()<<keylist;

//    QMap<QString, type_valueKey> maptest;
//    maptest[backZeroCommand] = type_valueKey(1);
//    maptest[glueFogCommand] = type_valueKey(1);
//    maptest[fogTimeCommand] = type_valueKey(30);
//    maptest[circulateCommand] = type_valueKey(20);
//    maptest["circulateBool"] = type_valueKey(1);

//    qDebug()<<maptest.value("testkey").getString();
//    qDebug()<<maptest.value("testint").getInt();
//    qDebug()<<maptest.value("testint").getBool();
//    qDebug()<<maptest.value("testfloat").getFloat();
//    qDebug()<<maptest.value("testfloat").getInt();
//    QString get = order_systemSetting(maptest);
//    qDebug()<<get;
}

void Json_handle::jsontest()
{
    json.insert(Json_AllCommand::loginCommand, QString("Qt"));
    json.insert(getCommandStringFromNum(2), 5);
    json.insert(CommandList.value(3), true);

    document.setObject(json);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    QString json_str(byte_array);
//    qDebug()<<json_str;

    QString testjson = "{\"CRC\":6607,\"FCS\":true,\"dataString\":\"{\\\"LimitAlarm\\\":\\\"aaad\\\"}\"}";

    QJsonParseError json_error;
//    QJsonDocument parse_doucment = QJsonDocument::fromRawData(testjson, testjson.size());
    QJsonDocument parse_doucment = QJsonDocument::fromJson(testjson.toUtf8(), &json_error);
    if(json_error.error == QJsonParseError::NoError){
        if(parse_doucment.isObject()){
            QJsonObject obj = parse_doucment.object();
            if(obj.contains("dataString")){
                QJsonValue dataString_value = obj.take("dataString");
                if(dataString_value.isString()){
                    QString dataString = dataString_value.toString();
//                    qDebug()<<dataString;
                    QJsonDocument parse_dataString = QJsonDocument::fromJson(dataString.toUtf8(), &json_error);
                    QJsonObject obj = parse_dataString.object();
                    if(obj.contains("LimitAlarm")){
                        QJsonValue LimitAlarm_value = obj.take("LimitAlarm");
                        QString limstring = LimitAlarm_value.toString();
//                        qDebug()<<limstring;
                    }
                }
            }
            if(obj.contains("CRC")){
                QJsonValue version_value = obj.take("CRC");
                if(version_value.isDouble()){
                    //int version = version_value.toVariant().toInt();
//                    qDebug()<<version;
                }
            }
            if(obj.contains("FCS")){
                QJsonValue version_value = obj.take("FCS");
                if(version_value.isBool())
                {
                    //bool flag = version_value.toBool();
//                    qDebug()<<flag;
                }
            }
        }
    }


}

/*生成登陆命令*/
QString Json_handle::order_login(QString UserName, QString PassWord, QString CheckNum)
{
    QJsonObject loginjson;
    QJsonObject tmpjson1;

    tmpjson1.insert("User", UserName);
    tmpjson1.insert("Password", PassWord);
    loginjson.insert(loginCommand, tmpjson1);
    loginjson.insert(setCheckNumCommand, CheckNum);

    QJsonDocument login_document;
    login_document.setObject(loginjson);
    QByteArray login_array = login_document.toJson(QJsonDocument::Compact);
    QString login_String(login_array);

//    qDebug()<<login_String;
    return login_String;
}

/*解析登陆返回命令(专用型)*/
int Json_handle::order_loginexplain(QString dataString)
{
//    QMap<QString,int> retmap;
    int ret;
    QJsonParseError json_error;
    QJsonDocument parse_doucment;
    parse_doucment = QJsonDocument::fromJson(dataString.toUtf8(), &json_error);
    if(json_error.error == QJsonParseError::NoError){
        QJsonObject obj = parse_doucment.object();
//        if(obj.contains(loginCommand)){
//            retmap.insert(loginCommand, obj.take(loginCommand).toInt());
//        }
//        if(obj.contains(setCheckNumCommand)){
//            retmap.insert(setCheckNumCommand, obj.take(setCheckNumCommand).toBool());
//        }
        int log = obj.value("Login").toInt();
//        int check = obj.value(setCheckNumCommand).toBool();
        ret = log;
    }
    return ret;
}

/*生成系统设置保存命令*/
QString Json_handle::order_systemSetting(shareMap dataMap)
{
    QJsonObject systemsettingjson;
    /*限位方向*/
    systemsettingjson.insert(xLimCommand, dataMap.value(xLimCommand).getBool());
    systemsettingjson.insert(yLimCommand, dataMap.value(yLimCommand).getBool());
    systemsettingjson.insert(zLimCommand, dataMap.value(zLimCommand).getBool());
    systemsettingjson.insert(uLimCommand, dataMap.value(uLimCommand).getBool());
    /*IO复用*/
    systemsettingjson.insert(IO0_ReUseCommand, dataMap.value(IO0_ReUseCommand).getBool());
    systemsettingjson.insert(IO1_ReUseCommand, dataMap.value(IO1_ReUseCommand).getBool());
    systemsettingjson.insert(IO2_ReUseCommand, dataMap.value(IO2_ReUseCommand).getBool());
    systemsettingjson.insert(IO3_ReUseCommand, dataMap.value(IO3_ReUseCommand).getBool());
    /*手动速度*/
    systemsettingjson.insert(manualSpeedCommand,dataMap.value(manualSpeedCommand).getInt());
    systemsettingjson.insert(backZeroSpeedCommand,dataMap.value(backZeroSpeedCommand).getInt());
    /*自动回零*/
    systemsettingjson.insert(backZeroCommand,dataMap.value(backZeroCommand).getBool());
    /*出胶前雾化*/
    systemsettingjson.insert(glueFogCommand,dataMap.value(glueFogCommand).getBool());
    /*雾化时间*/
    systemsettingjson.insert(fogTimeCommand,dataMap.value(fogTimeCommand).getInt());
    /*循环启动*/
    systemsettingjson.insert(circulateCommand,
            getBitJsonObject(dataMap.value("circulateBool").getBool(), dataMap.value(circulateCommand).getInt()));

    QJsonDocument systemseting_document;
    systemseting_document.setObject(systemsettingjson);
    QByteArray systemseting_array = systemseting_document.toJson(QJsonDocument::Compact);
    QString systemseting_String(systemseting_array);
    return systemseting_String;
}

/*生成运行设置保存命令*/
QString Json_handle::order_motionSetting(shareMap dataMap,bool enableFlag[])
{
    QJsonObject jsonObject;
    bool axisbool[4];
    for(int i = 0; i < 4; i++){
        if(enableFlag[i]>0) axisbool[i] = true;
        else axisbool[i] = false;
    }
    int axisenable = axisbool[3]*8 + axisbool[2]*4 + axisbool[1]*2 + axisbool[0]*1;

    //X轴
    if(axisbool[0]){
        jsonObject.insert(xDPRCommand,dataMap.value(xDPRCommand).getFloat());
        jsonObject.insert(xPPRCommand,dataMap.value(xPPRCommand).getInt());
        jsonObject.insert(x_BackZeroDirCommand,dataMap.value(x_BackZeroDirCommand).getBool());
        jsonObject.insert(x_MaxSpeedCommand,dataMap.value(x_MaxSpeedCommand).getInt());
        jsonObject.insert(x_AccelerateCommand,dataMap.value(x_AccelerateCommand).getInt());
        jsonObject.insert(x_MotorDirCommand,dataMap.value(x_MotorDirCommand).getBool());
        jsonObject.insert(xAddLimitDisCommand,dataMap.value(xAddLimitDisCommand).getFloat());
        jsonObject.insert(xReduceLimitDisCommand,dataMap.value(xReduceLimitDisCommand).getFloat());
    }

    //Y轴
    if(axisbool[1]){
        jsonObject.insert(yDPRCommand,dataMap.value(yDPRCommand).getFloat());
        jsonObject.insert(yPPRCommand,dataMap.value(yPPRCommand).getInt());
        jsonObject.insert(y_BackZeroDirCommand,dataMap.value(y_BackZeroDirCommand).getBool());
        jsonObject.insert(y_MaxSpeedCommand,dataMap.value(y_MaxSpeedCommand).getInt());
        jsonObject.insert(y_AccelerateCommand,dataMap.value(y_AccelerateCommand).getInt());
        jsonObject.insert(y_MotorDirCommand,dataMap.value(y_MotorDirCommand).getBool());
        jsonObject.insert(yAddLimitDisCommand,dataMap.value(yAddLimitDisCommand).getFloat());
        jsonObject.insert(yReduceLimitDisCommand,dataMap.value(yReduceLimitDisCommand).getFloat());
    }

    //Z轴
    if(axisbool[2]){
        jsonObject.insert(zDPRCommand,dataMap.value(zDPRCommand).getFloat());
        jsonObject.insert(zPPRCommand,dataMap.value(zPPRCommand).getInt());
        jsonObject.insert(z_BackZeroDirCommand,dataMap.value(z_BackZeroDirCommand).getBool());
        jsonObject.insert(z_MaxSpeedCommand,dataMap.value(z_MaxSpeedCommand).getInt());
        jsonObject.insert(z_AccelerateCommand,dataMap.value(z_AccelerateCommand).getInt());
        jsonObject.insert(z_MotorDirCommand,dataMap.value(z_MotorDirCommand).getBool());
        jsonObject.insert(zAddLimitDisCommand,dataMap.value(zAddLimitDisCommand).getFloat());
        jsonObject.insert(zReduceLimitDisCommand,dataMap.value(zReduceLimitDisCommand).getFloat());
    }

    //U轴
    if(axisbool[3]){
        jsonObject.insert(uDPRCommand,dataMap.value(uDPRCommand).getFloat());
        jsonObject.insert(uPPRCommand,dataMap.value(uPPRCommand).getInt());
        jsonObject.insert(u_BackZeroDirCommand,dataMap.value(u_BackZeroDirCommand).getBool());
        jsonObject.insert(u_MaxSpeedCommand,dataMap.value(u_MaxSpeedCommand).getInt());
        jsonObject.insert(u_AccelerateCommand,dataMap.value(u_AccelerateCommand).getInt());
        jsonObject.insert(u_MotorDirCommand,dataMap.value(u_MotorDirCommand).getBool());
        jsonObject.insert(uAddLimitDisCommand,dataMap.value(uAddLimitDisCommand).getFloat());
        jsonObject.insert(uReduceLimitDisCommand,dataMap.value(uReduceLimitDisCommand).getFloat());
    }
    /*旋转轴设置*/
    jsonObject.insert(rotationAxisCommand, dataMap.value(rotationAxisCommand).getInt());
    /*电机类型*/
    jsonObject.insert(axisStyleCommand, dataMap.value(axisStyleCommand).getInt());
    /*电机使能*/
    jsonObject.insert(axisEnableCommand, axisenable);

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray motionseting_array = jsonObject_document.toJson(QJsonDocument::Compact);
    QString motionseting_String(motionseting_array);
    return motionseting_String;
}

//生成运动参数请求命令
QString Json_handle::order_getMontionSetting()
{
    QJsonObject jsonObject;
    jsonObject.insert("MotionSetting", "");

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray motionseting_array = jsonObject_document.toJson(QJsonDocument::Compact);
    QString getmotionseting_String(motionseting_array);
    return getmotionseting_String;
}

//生成系统参数请求命令
QString Json_handle::order_getSytemSetting()
{
    QJsonObject jsonObject;
    jsonObject.insert("SystemSetting", "");

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray motionseting_array = jsonObject_document.toJson(QJsonDocument::Compact);
    QString getmotionseting_String(motionseting_array);
    return getmotionseting_String;
}

//生成DIDOAIAO状态查询命令
QString Json_handle::order_IODiagnose(int value, bool flag,QList<float> AOList)
{
    QJsonObject jsonObject;
    QJsonArray jsonArray;
    QJsonArray AOitem;
    jsonArray<<value;
    jsonArray<<flag;
    jsonObject.insert(dOCommand, jsonArray);
    jsonObject.insert(dICommand, "");

    for(int i = 0; i < AOList.size(); i++){
        QJsonArray AOjsonArray;
        AOjsonArray<<i;
        AOjsonArray<<AOList.at(i);
        AOitem<<AOjsonArray;
    }
    jsonObject.insert(aOCommand, AOitem);
    jsonObject.insert(aICommand, "");
    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray diagnose_ba = jsonObject_document.toJson(QJsonDocument::Compact);
    QString diagnoseString(diagnose_ba);
    return diagnoseString;
}
/*生成手动设置坐标+手动+回零请求生成*/
QString Json_handle::order_manualDiagnose(int num, bool stat, int backzero)
{
    QJsonObject jsonObject;
    switch (num) {
    case 1: // x+
        jsonObject.insert(xAddMoveCommand, stat);
        break;
    case 0: // x-
        jsonObject.insert(xReduceMoveCommand, stat);
        break;
    case 3: // y+
        jsonObject.insert(yAddMoveCommand, stat);
        break;
    case 2: // y-
        jsonObject.insert(yReduceMoveCommand, stat);
        break;
    case 5: // z+
        jsonObject.insert(zAddMoveCommand, stat);
        break;
    case 4: // z-
        jsonObject.insert(zReduceMoveCommand, stat);
        break;
    case 7: // u+
        jsonObject.insert(uAddMoveCommand, stat);
        break;
    case 6: // u-
        jsonObject.insert(uReduceMoveCommand, stat);
        break;
    default:
        break;
    }
    jsonObject.insert(x_CoordinateCommand, "");
    jsonObject.insert(y_CoordinateCommand, "");
    jsonObject.insert(z_CoordinateCommand, "");
    jsonObject.insert(u_CoordinateCommand, "");
    jsonObject.insert(limitAlarmCommand, "");

    if(backzero != 5){
        QString bzcmd = "S";
        switch (backzero){
        case 0:
            bzcmd = "X";
            break;
        case 1:
            bzcmd = "Y";
            break;
        case 2:
            bzcmd = "Z";
            break;
        case 3:
            bzcmd = "U";
            break;
        default:
            break;
        }
        jsonObject.insert(axisBackzeroCommand, bzcmd);
    }

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray diagnose_ba = jsonObject_document.toJson(QJsonDocument::Compact);
    QString diagnoseString(diagnose_ba);
    return diagnoseString;
}
/*生成运行界面语句 坐标+限位+行号+速度+产量+时间+运行状态*/
QString Json_handle::order_runningstatus()
{
    QJsonObject jsonObject;
    jsonObject.insert(x_CoordinateCommand, "");
    jsonObject.insert(y_CoordinateCommand, "");
    jsonObject.insert(z_CoordinateCommand, "");
    jsonObject.insert(u_CoordinateCommand, "");
    jsonObject.insert(limitAlarmCommand, "");
    jsonObject.insert(checkLineNumCommand, "");
    jsonObject.insert(currentSpeedCommand, "");
    jsonObject.insert(runTimeCommand, "");
    jsonObject.insert(outPutCommand, "");
    jsonObject.insert(runStateCommand, "");

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray diagnose_ba = jsonObject_document.toJson(QJsonDocument::Compact);
    QString diagnoseString(diagnose_ba);
    return diagnoseString;
}
/*生成查询下位机是否准备就绪命令 运行文件+运行状态*/
QString Json_handle::order_readyStatus()
{
    QJsonObject jsonObject;
    jsonObject.insert(runFileCommand, "");
    jsonObject.insert(runStateCommand, "");

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray diagnose_ba = jsonObject_document.toJson(QJsonDocument::Compact);
    QString diagnoseString(diagnose_ba);
    return diagnoseString;
}
/*生成开始运行命令*/
QString Json_handle::order_runContral(int num)
{
    QJsonObject jsonObject;
    switch(num){
    case Start:
        jsonObject.insert(runStartCommand, "");
        break;
    case Stop:
        jsonObject.insert(runStopCommand, "");
        break;
    case Pause:
        jsonObject.insert(runPauseCommand, "");
        break;
    case Reset:
        jsonObject.insert(runResetCommand, "");
        break;
    }

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray diagnose_ba = jsonObject_document.toJson(QJsonDocument::Compact);
    QString diagnoseString(diagnose_ba);
    return diagnoseString;
}
/*生成JCODE传送语句*/
QString Json_handle::order_jcodeString(QString filename, QStringList jcodeString)
{
    QJsonObject jsonObject;
    QJsonArray jcodeArray;

    jsonObject.insert(fileNameCommand, filename);
    for(int i = 0; i < jcodeString.size(); i++){
        //utf8转gbk
        jcodeArray<<jcodeString.at(i);
    }
    jsonObject.insert(jCodeCommand, jcodeArray);

    QJsonDocument jsonObject_document;
    jsonObject_document.setObject(jsonObject);
    QByteArray jcode_ba = jsonObject_document.toJson(QJsonDocument::Compact);//utf8

    QString jcodeJsonString(jcode_ba);
//    QByteArray gbkstring = jcodeJsonString.toLocal8Bit();//gbk
//    qDebug()<<"CRC"<<jcode_ba<<order_jcodeCrcexplain(gbkstring);
    return jcodeJsonString;
}
/*解析返回命令(通用型) 入围原始jsonstring则QMap中包括crc fsc dataString*/
QMap<QString,QString> Json_handle::order_replyexplain(QString replyString)
{
    QMap<QString,QString> retmap;

    QJsonParseError json_error;
    QJsonDocument parse_doucment;

    QStringList keylist = getJsonObjectNameString(replyString);
    if(keylist.isEmpty()){
        return retmap;
    }
    parse_doucment = QJsonDocument::fromJson(replyString.toUtf8(), &json_error);
    QJsonObject obj = parse_doucment.object();
    for(int i = 0; i < keylist.size(); i++){
        if(obj.contains(keylist.at(i))){
            retmap.insert(keylist.at(i), obj.value(keylist.at(i)).toVariant().toString());
        }
    }
    return retmap;
}

QStringList Json_handle::getJsonObjectNameString(QString dataString)
{
    QJsonParseError json_error;
    QJsonDocument parse_doucment;
    try{
        parse_doucment = QJsonDocument::fromJson(dataString.toUtf8(), &json_error);
        if(json_error.error != QJsonParseError::NoError){
            throw (int)json_error.error;
        }
    }catch(int exception){
        qDebug()<<"getJsonObjectNameString error"<<exception;
        QStringList nullList;
        return nullList;
    }
    QJsonObject obj = parse_doucment.object();
    return obj.keys();
}

/*组装json包*/
QString Json_handle::order_makeup(int Crc, int Fcs, QString DataString)
{
    QJsonObject madeJson;

    madeJson.insert("CRC", Crc);
    madeJson.insert("FCS", Fcs);
    madeJson.insert("dataString", DataString);

    QJsonDocument made_document;
    made_document.setObject(madeJson);
    QByteArray made_array = made_document.toJson(QJsonDocument::Compact);
    QString madeString(made_array);
    madeString = madeString + "\r\n";
    //qDebug()<<madeString;
    return madeString;
}

QJsonArray Json_handle::getBitJsonObject(bool flag, int flag2){
    QJsonArray jsonArray;
    jsonArray.insert(jsonArray.size(),flag);
    jsonArray.insert(jsonArray.size(),flag2);
    return jsonArray;
}

/*JCODE特殊加校验*/
int Json_handle::order_jcodeCrcexplain(QString resultString)
{
    unsigned short MSBInfo ;
    unsigned short wCrcData;
    unsigned short nIndexI,nIndexJ;
//    QByteArray p= resultString.toLocal8Bit();
    const char *p = resultString.toStdString().data();
    wCrcData=0xffff;
    for(nIndexI = 0; nIndexI < (resultString.length()); nIndexI++){
        wCrcData = wCrcData ^ p[nIndexI];
        for(nIndexJ = 0; nIndexJ < 8; nIndexJ++){
            MSBInfo = wCrcData & 0x0001;
            wCrcData = wCrcData  >> 1;
            if(MSBInfo != 0 ){
                wCrcData = wCrcData ^ 0xa001;
            }
        }
    }
    return wCrcData;
}

/*JCODE特殊加校验2*/
int Json_handle::order_jcodeCrcexplain(QByteArray b)
{
    static int MSBInfo ;
    static unsigned short wCrcData;
    static unsigned short nIndexI,nIndexJ;
    char *p = b.data();
    wCrcData=0xffff;
    for(nIndexI = 0; nIndexI < b.length() ; nIndexI ++)
    {
        wCrcData = wCrcData ^ (unsigned char)p[nIndexI];
        for(nIndexJ = 0; nIndexJ < 8; nIndexJ ++)
        {
            MSBInfo = wCrcData & 0x0001;
            wCrcData = wCrcData  >> 1;
            if(MSBInfo != 0 )
            {
                wCrcData = wCrcData ^ 0xa001;
            }
        }
    }
    return wCrcData;
}

/*加校验，返回校验码*/
int Json_handle::order_crcexplain(QString resultString)
{
    unsigned short MSBInfo ;
    unsigned short wCrcData;
    unsigned short nIndexI,nIndexJ;
    QByteArray p= resultString.toLatin1();
    wCrcData=0xffff;
    for(nIndexI = 0; nIndexI < (resultString.length()); nIndexI++){
        wCrcData = wCrcData ^ p[nIndexI];
        for(nIndexJ = 0; nIndexJ < 8; nIndexJ++){
            MSBInfo = wCrcData & 0x0001;
            wCrcData = wCrcData  >> 1;
            if(MSBInfo != 0 ){
                wCrcData = wCrcData ^ 0xa001;
            }
        }
    }
    return wCrcData;
}
